package com.aiyun.rabbit.rabbitdemo.order.resource;

import com.aiyun.rabbit.rabbitdemo.dto.OrderDTO;
import com.aiyun.rabbit.rabbitdemo.dto.OrderStatus;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import static org.slf4j.LoggerFactory.getLogger;

@RestController
public class OrderResource {


	private final RabbitTemplate rabbitTemplate;
	private final Logger log = getLogger(OrderResource.class);

	public OrderResource(RabbitTemplate rabbitTemplate) {
		this.rabbitTemplate = rabbitTemplate;
	}

	@PostMapping("/order")
	public ResponseEntity<String> addOrder(@RequestBody OrderDTO orderDTO) throws JsonProcessingException {
		orderDTO.setOrderStatus(OrderStatus.STOCK_CONFIRMING);
		String json = new ObjectMapper().writeValueAsString(orderDTO);
		rabbitTemplate.convertAndSend(
				"exchange.stock",
				"confirm",
				json
		);

		rabbitTemplate.convertAndSend(
				"exchange.order",
				"delay-order-check",
				json
		);
		return ResponseEntity.ok("send success!");
	}
}
